from odoo import api, models, fields
from odoo.exceptions import ValidationError
from odoo.release import description


class QualityCheck(models.Model):
    _name = 'quality.check'
    _inherit = ['quality.check', 's.mes.upload']
    _warehouse_barcode = {
        'WH-STOCK-PP-PRODUCT': 'PP',
        'WH-STOCK-FREEZE-PRODUCT': 'RM',
        'WH-STOCK-SUBSRRATE-PRODUCT': 'PM',
        'WH-STOCK-FINISHED-PRODUCT': 'PD'
    }
    def do_fail(self):
        res = super().do_fail()
        if self.s_from_wms:
            self.sudo().with_delay(description='入库质检失败TO-WMS').wms_post_async()
        return res

    def do_pass(self):
        # wms接收的，质检后自动入库
        res = super().do_pass()
        if self.s_from_wms and self.quality_state == 'fail':
            raise ValidationError('wms入库质检失败后不允许再次通过')
        return res

    def wms_post_async(self, type=2, method='/JehaitWS/JOVETG/ReturnGoodsOut'):
        infos = []
        vals = {"reqTime": fields.Datetime.to_string(fields.Datetime.now()), 'PO': self.picking_id.name, 'detailInfos': []}
        barcode = self.move_line_id.location_dest_id.barcode
        infos.append({
            "POLine": self.picking_id.name + '-' + str(self.picking_id.purchase_id.id) + '-' + str(self.move_id.id),
            "Type": type,
            "MaterialID": self.move_id.product_id.default_code,
            "MaterialName": self.move_id.product_id.name,
            "MatCount": self.s_product_qty,
            "Batch": self.lot_name,
            "WarehouseID": self._warehouse_barcode[barcode] if barcode and barcode in self._warehouse_barcode.keys() else None
        })
        if infos:
            vals['detailInfos'] = infos
            self.wms_upload_data(vals, method)